from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler

from app import *
from app import static
from app.views import view


def checkexe(c):
    for process in c.Win32_Process():
        if process.Name in ["manage.exe", "manage.py"]:
            return True
    return False


def net_is_used(port, ip):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(1)
    sign = True
    try:
        s.connect((ip, port))
        s.shutdown(2)
        sign = True
    except:
        sign =  False
    finally:
        s.close()
    return sign


if __name__ == '__main__':
    # host = "192.168.43.224"
    host = "127.0.0.1"
    port = 8001  # 端口
    c = wmi.WMI()

    if 0 and checkexe(c):
        sys.exit(1)

    if not net_is_used(port,host):
        print(f"Local: http://{host}:{port}/")
        server = pywsgi.WSGIServer((host, port), app, handler_class=WebSocketHandler)
        webbrowser.open(f"http://{host}:{port}/")
        server.serve_forever()

